// Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "memento_common.h"
#include "mount_handler.h"

#include <stdio.h>

using std::string;

namespace chromeos_memento_updater {

MountHandler::MountHandler(const string& device_path,
                           const string& file_system,
                           unsigned long mount_flags) {
  char mount_template[] = "/tmp/mount_XXXXXX";
  mount_point_.assign(mkdtemp(mount_template));
  if (mount_point_.empty()) {
    error_exit("Failed to create mount point");
  }
  if (mount(device_path.c_str(), mount_point_.c_str(),
      file_system.c_str(), mount_flags, "") != 0) {
    error_exit("Cannot mount device " + device_path);
  }
}

string MountHandler::GetMountPoint() {
  return mount_point_;
}

MountHandler::~MountHandler() {
  if (umount(mount_point_.c_str()) != 0) {
    error("Cannot ummount device " + mount_point_);
  }
  if (remove(mount_point_.c_str()) != 0) {
    error("Cannot remove mount point");
  }
}

}  // namespace chromeos_memento_updater

